package com.bigshen.springcloud.demo.springcloudgateway8080;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

@Component
public class ShenDefineGatewayFilterFactory extends AbstractGatewayFilterFactory<ShenDefineGatewayFilterFactory.ShenConfig> {

    Logger logger = LoggerFactory.getLogger(ShenDefineGatewayFilterFactory.class);

    private static final String NAME_KEY = "name";

    public ShenDefineGatewayFilterFactory() {
        super(ShenConfig.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList(NAME_KEY);
    }

    @Override
    public GatewayFilter apply(ShenConfig config) {

        // Filter pre/post

        return (((exchange, chain) -> {
            // 过滤器 pre
            logger.info("[Pre] Filter Request, name: " + config.getName());
            // TODO before
            return chain.filter(exchange) // 处理
                    .then(Mono.fromRunnable(()-> { // then，响应式编程，当前一步骤 chain.filter 处理结束，进入then逻辑进行处理
                        // 内部回调
                        // 过滤器 post

                        // TODO after
                        logger.info("[post]: Response Filter");
                    }));

        }));
    }

    public static class ShenConfig {

        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

}
